<?php

namespace app\company\controller\user\config;

use app\admin\service\ConsultantExportService;
use app\admin\service\userSeniorExportService;
use app\BaseController;
use app\model\ConfigModel;
use app\model\ConsultOfflineModel;
use app\model\ConsultOnlineModel;
use app\model\ConsultQuestionModel;
use app\model\DepartmentLevelModel;
use app\model\DepartmentModel;
use app\model\RoleModel;
use app\model\UnitModel;
use app\model\UserModel;
use think\App;

class Index extends BaseController
{

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 部门选择器2
     * @return bool|string
     */
    public function selector2(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位ID'  =>  'require',
            ]);
            $DepartmentModel = new DepartmentModel();
            $data = $DepartmentModel->where('unit_id','=',$param['unit_id'])
                ->withCount('users')
                ->withCount('departmentAdmins')
                ->select()->toArray();
            foreach ($data as &$item) {
                $getAllSubcategories = getAllSubcategories($data, $item['id']);
                $users_count = array_column($getAllSubcategories, 'users_count');
                $users_count = array_sum($users_count);
                $item['users_count'] = $item['users_count'] + $users_count;
            }
            return success(buildTree($data));
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 部门
     * @return bool|string
     */
    public function department(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位ID'  =>  'require',
            ]);
            $DepartmentModel = new DepartmentModel();
            $data = $DepartmentModel->where('unit_id','=',$param['unit_id'])
                ->withCount('users')
                ->withCount('departmentAdmins')
                ->select()->toArray();
            foreach ($data as &$item){
                $getAllSubcategories = getAllSubcategories($data,$item['id']);
                $users_count = array_column($getAllSubcategories,'users_count');
                $users_count = array_sum($users_count);
                $item['users_count'] = $item['users_count'] + $users_count;
            }
            $UnitModel = new UnitModel();
            $unit_name = $UnitModel->where('id','=',$this->userData['unit_id'])->value('name');
            return success(['list' => buildTree($data), 'total' => count($data), 'name' => $unit_name]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取系统设置参数
     * @return bool|string
     */
    public function getConfig(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'key|键'  =>  'require',
                'unit_id|单位ID'  =>  'require',
            ]);
            $ConfigModel = new ConfigModel();
            $data = $ConfigModel->where([
                'unit_id' => $param['unit_id'],
                'key' => $param['key']
            ])->value('value')??'';
            $data = json_decode($data,true);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 部门等级规则列表
     * @return false|string
     */
    public function departmentLevelList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位ID'  =>  'require',
            ]);
            $DepartmentLevelModel = new DepartmentLevelModel();
            $list = $DepartmentLevelModel->where('unit_id','=',$param['unit_id'])->select()->toArray();
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 指定部门管理员选项列表
     * @return false|string
     */
    public function adminUserList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位ID'  =>  'require',
            ]);
            $UserModel = new UserModel();
            $RoleModel = new RoleModel();
            $role_id = $RoleModel->where([
                ['unit_id','=',$param['unit_id']],
                ['mode','=',1]
            ])->value('id');
            $list = $UserModel->field('id,name')
                ->where([
                    'unit_id' => $param['unit_id'],
                    'role_id' => $role_id
                ])->select()->toArray();
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 部门选择器
     */
    public function departmentSelector(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'level|等级'  =>  'require',
                'unit_id|单位ID'  =>  'require',
            ]);
            $DepartmentModel = new DepartmentModel();
            $data = $DepartmentModel->field('id,name,mode,stage,number')
                ->with('departmentLevel')
                ->where([
                    'unit_id' => $param['unit_id'],
                    'level' => $param['level']
                ])->select()->toArray();
            foreach ($data as &$item) {
                $item['level_rules'] = isset($item['level_rules'])?json_decode($item['level_rules'],true):[];
                $item['stage_name'] = $item['level_rules'][$item['stage']] ?? '';
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 高级筛选-导出【普通用户】
     * @return bool|string
     */
    public function userSeniorExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位ID'  =>  'require',
            ]);
            $param['role_mode'] = 0;
            $param['user_id'] = 0;
            $userSeniorExportService = new userSeniorExportService($this->app);
            $ret = $userSeniorExportService->userSeniorExport($param);
            if (!$ret) throw new \Exception($userSeniorExportService->getMessage());
            return success($userSeniorExportService->getResult());
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 高级筛选-导出【普通用户id集合】
     * @return bool|string
     */
    public function getUserIdExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位ID'  =>  'require',
            ]);
            $param['role_mode'] = 0;
            $param['user_id'] = 0;
            $userSeniorExportService = new userSeniorExportService($this->app);
            $ret = $userSeniorExportService->getUserIdExport($param);
            if (!$ret) throw new \Exception($userSeniorExportService->getMessage());
            return success($userSeniorExportService->getResult());
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 高级筛选-导出【获取咨询师ID】
     * @return bool|string
     */
    public function getConsultantIdExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位ID'  =>  'require',
            ]);
            $param['role_mode'] = 0;
            $param['user_id'] = 0;
            $consultantSeniorExportService = new ConsultantExportService($this->app);
            $ret = $consultantSeniorExportService->getConsultantIdExport($param);
            if (!$ret) throw new \Exception($consultantSeniorExportService->getMessage());
            return success($ret);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 按问题分类统计-个人
     * @return bool|string
     */
    public function OneQuestionType(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位ID'  =>  'require',
                'consult_id|咨询师ID'  =>  'require',
            ]);
            $ConsultQuestionModel = new ConsultQuestionModel();
            $ConsultOnlineModel = new ConsultOnlineModel();
            $ConsultOfflineModel = new ConsultOfflineModel();
            $question = $ConsultQuestionModel->field('id,name')->where([
                ['unit_id','=',$param['unit_id']],
                ['status','=',1]
            ])->select()->toArray();
            $data = [];
            foreach ($question as $item) {
                $data['name'][] = $item['name'];
                $ConsultOnlineUid = $ConsultOnlineModel->where([
                    ['consult_id','=',$param['consult_id']],
                    ['question_id','=',$item['id']],
                ])->distinct(true)->column('uid');
                $ConsultOfflineUid = $ConsultOfflineModel->where([
                    ['consult_id','=',$param['consult_id']],
                    ['question_id','=',$item['id']],
                ])->distinct(true)->column('uid');
                $uid = array_merge($ConsultOnlineUid,$ConsultOfflineUid);
                $uid = array_unique($uid);
                $data['num'][] = count($uid);
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 高级筛选-导出【咨询师】
     * @return bool|string
     */
    public function consultantSeniorExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位ID'  =>  'require',
            ]);
            $param['role_mode'] = 0;
            $param['user_id'] = 0;
            $consultantSeniorExportService = new ConsultantExportService($this->app);
            $ret = $consultantSeniorExportService->consultantSeniorExport($param);
            if (!$ret) throw new \Exception($consultantSeniorExportService->getMessage());
            return success($consultantSeniorExportService->getResult());
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 累计接待人数统计-个人
     * @return bool|string
     */
    public function OneReceptionCapacity(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位ID'  =>  'require',
                'consult_id|咨询师ID'  =>  'require',
            ]);
            $UserModel = new UserModel();
            $ConsultOnlineModel = new ConsultOnlineModel();
            $ConsultOfflineModel = new ConsultOfflineModel();
            $ConsultOnlineCount = $ConsultOnlineModel->where([
                ['unit_id','=',$param['unit_id']],
                ['consult_id','=',$param['consult_id']],
            ])->count();
            $ConsultOfflineCount = $ConsultOfflineModel->where([
                ['unit_id','=',$param['unit_id']],
                ['consult_id','=',$param['consult_id']],
            ])->count();
            $ConsultOnlineUid = $ConsultOnlineModel->where([
                ['unit_id','=',$param['unit_id']],
                ['consult_id','=',$param['consult_id']],
            ])->distinct(true)->column('uid');
            $ConsultOfflineUid = $ConsultOfflineModel->where([
                ['unit_id','=',$param['unit_id']],
                ['consult_id','=',$param['consult_id']],
            ])->distinct(true)->column('uid');
            $ConsultOnlineTotal = count($ConsultOnlineUid);
            if ($ConsultOnlineTotal > 0){
                $ConsultOnlineBoy = $UserModel->where([
                    ['id','in',$ConsultOnlineUid],
                    ['sex','=',1]
                ])->count('id');
                $ConsultOnlineGirl = $ConsultOnlineTotal - $ConsultOnlineBoy;
            }else{
                $ConsultOnlineBoy = 0;
                $ConsultOnlineGirl = 0;
            }
            $ConsultOfflineTotal = count($ConsultOfflineUid);
            if ($ConsultOfflineTotal > 0){
                $ConsultOfflineBoy = $UserModel->where([
                    ['id','in',$ConsultOfflineUid],
                    ['sex','=',1]
                ])->count('id');
                $ConsultOfflineGirl = $ConsultOfflineTotal - $ConsultOfflineBoy;
            }else{
                $ConsultOfflineBoy = 0;
                $ConsultOfflineGirl = 0;
            }
            return success([
                'ConsultOnlineCount' => $ConsultOnlineCount,
                'ConsultOfflineCount' => $ConsultOfflineCount,
                'ConsultOnlineBoy' => $ConsultOnlineBoy,
                'ConsultOnlineGirl' => $ConsultOnlineGirl,
                'ConsultOfflineBoy' => $ConsultOfflineBoy,
                'ConsultOfflineGirl' => $ConsultOfflineGirl
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 月度人数统计-个人
     * @return bool|string
     */
    public function OneMonthPeopleNumber(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'unit_id|单位ID'  =>  'require',
                'consult_id|咨询师ID'  =>  'require',
            ]);
            $ConsultOnlineModel = new ConsultOnlineModel();
            $ConsultOfflineModel = new ConsultOfflineModel();
            $UserModel = new UserModel();
            $data = [];
            for ($i=1;$i<=12;$i++){
                $start_time = strtotime(date('Y-'.$i.'-01'));
                $end_time = strtotime(date('Y-'.$i.'-t 23:59:59'));
                $data['date'][] = date('Y-m',$start_time);
                $ConsultOnlineUid = $ConsultOnlineModel->where([
                    ['unit_id','=',$param['unit_id']],
                    ['consult_id','=',$param['consult_id']],
                    ['time','between',[$start_time,$end_time]]
                ])->distinct(true)->column('uid');
                $ConsultOfflineUid = $ConsultOfflineModel->where([
                    ['unit_id','=',$param['unit_id']],
                    ['consult_id','=',$param['consult_id']],
                    ['time','between',[$start_time,$end_time]]
                ])->distinct(true)->column('uid');
                $uid = array_merge($ConsultOnlineUid,$ConsultOfflineUid);
                $uid = array_unique($uid);
                $data['boy'][] = $UserModel->where([
                    ['id','in',$uid],
                    ['sex','=',1]
                ])->count('id');
                $data['girl'][] = $UserModel->where([
                    ['id','in',$uid],
                    ['sex','=',2]
                ])->count('id');
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}